package ${package.Controller};

import lombok.extern.slf4j.Slf4j;
import org.layuiframework.stereotype.security.VerifyCode;
import org.layuiframework.stereotype.security.bean.AbstractUser;
import org.layuiframework.stereotype.security.bean.LoginUser;
import org.layuiframework.stereotype.security.impl.AbstractUserGetter;
import org.layuiframework.stereotype.security.impl.CacheServiceImpl;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
<#if ES_URIS??>
import org.springframework.context.annotation.Import;
import org.layuiframework.stereotype.elasticsearch.ElasticsearchConfiguration;
import org.layuiframework.stereotype.elasticsearch.ElasticsearchHandlers;
import org.layuiframework.stereotype.elasticsearch.ElasticsearchRecord;
import org.layuiframework.stereotype.elasticsearch.ElasticsearchVo;
import org.springframework.web.bind.annotation.RequestBody;
import java.util.List;
</#if>

/**
 * <p>
 * 验证码控制器
 * </p>
 *
 * @author ${author}
 * @since ${date}
 */
@Slf4j
@RestController
@RequestMapping("/index")
<#if ES_URIS??>
@Import(ElasticsearchConfiguration.class)
</#if>
public class IndexController{

    @Resource
    CacheServiceImpl cache;

    @Resource
    AbstractUserGetter getter;
<#if ES_URIS??>

    @Resource
    ElasticsearchHandlers elasticsearchHandlers;
</#if>

<#assign genericity = 'String' />
    @PostMapping("/vercode")
    public Map<${genericity}, ${genericity}> code(HttpServletRequest req, HttpServletResponse resp, String crc) throws IOException {
        Map<${genericity}, ${genericity}> res = new HashMap<${genericity}, ${genericity}>();
        try {
            VerifyCode vc = new VerifyCode();
            BufferedImage image = vc.getImage();
            res = new HashMap<${genericity}, ${genericity}>();
            res.put("image", vc.getBase64Image(image));
            // 测试时查看，实际不需要返回
            // res.put("code", vc.getText());
            LoginUser loginUser = new LoginUser();
            loginUser.setClientId(crc);
            loginUser.setVerifyCode(vc.getText());
            cache.setVerifyCode(loginUser);
        } catch (IOException e) {
            log.error("生成验证码失败");
            e.printStackTrace();
        }
        res.put("msg","验证码");
        return res;
    }
<#if ES_URIS??>

<#assign elasticsearchRecord = 'ElasticsearchRecord' />
    @PostMapping("/search")
    public Map<${genericity}, List<${elasticsearchRecord}>> search(@RequestBody ElasticsearchVo vo){
        return elasticsearchHandlers.search(vo);
    }
</#if>

}

